import os
import logging

# 配置日志
logging.basicConfig(
    filename='file_rename.log',  # 日志文件名
    level=logging.INFO,          # 日志级别
    format='%(asctime)s - %(levelname)s - %(message)s',  # 日志格式
)

def rename_files_in_directory(directory, rename_function):
    try:
        # 遍历目录中的所有文件和子目录
        for root, dirs, files in os.walk(directory):
            for file_name in files:
                try:
                    # 获取文件的完整路径
                    old_file_path = os.path.join(root, file_name)
                    # 使用传入的重命名函数生成新文件名
                    new_file_name = rename_function(file_name)
                    new_file_path = os.path.join(root, new_file_name)
                    
                    # 检查新文件名是否已存在，避免冲突
                    if os.path.exists(new_file_path):
                        logging.warning(f"File already exists: {new_file_path}, skipping rename.")
                        continue
                    
                    # 重命名文件
                    os.rename(old_file_path, new_file_path)
                    logging.info(f"Renamed: {old_file_path} -> {new_file_path}")
                
                except Exception as e:
                    # 捕获单个文件重命名时的异常并记录错误信息
                    logging.error(f"Failed to rename {file_name} in {root}: {str(e)}")
    except Exception as e:
        # 捕获整个遍历过程中可能出现的异常
        logging.critical(f"Critical error while processing directory {directory}: {str(e)}")

def simple_rename(file_name):
    # 简单的重命名函数，将文件名全部改为小写
    return "灾备中心备份系统巡检表运行情况({}).pdf".format(file_name.split("-")[1][0:11])

if __name__ == "__main__":
    # 指定需要处理的目录路径
    directory_path = 'E:\\06'

    # 调用重命名函数
    rename_files_in_directory(directory_path, simple_rename)
